#! C:\Perl\bin\perl.exe

# Copyright (c) 2010, College Center for Library Automation

# See the included Copyright.txt file for full license

#
# 
#
use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use HTTP::Request::Common;
use Date::Calc qw(Decode_Month Add_Delta_YM Today Delta_YMD);
use Text::CSV;

use avsCommon;


my ($content, $response, $request, $url);

dbsetup();

do {
	getStats ();
} while ($sthlogin->fetch);

dbshutdown();

exit;

sub getStats {
	my $ua = new LWP::UserAgent(keep_alive=>1);
	$ua->cookie_jar( {} );	

	$url = "http://www.stats.oclc.org/cusp/login";
	$request = HTTP::Request->new(POST => $url);
	$request->content_type('application/x-www-form-urlencoded');
	$request->content("username=$username&password=$password&next=html%2Fhome.html&bad=error%2Fbadlogin_en.html&entityjavascript=false&entityscreensize=unknown");
	
	$response = $ua->request($request);
	if (!$response->is_success && substr($response->status_line,0,3) != 302) {
		die "#error:$0: POST login $url" . $response->status_line;
	};

	my ($runyear, $runmonth, $runday);
	# setup the date parameters for the loop. 
	if ($begyear == $endyear) {
		($runyear, $runmonth, $runday) = @enddate;	# same year collect to enddate
	}
	else {
		($runyear, $runmonth) = ($begyear, 12);	# previous years collect to december of that year
	};

	# run once for each year covered by beg and end date. typically beg and end month the same.
	while ($runyear <= $endyear) {

	# setup the date parameters for the url
		my $yyyymm = sprintf('%04d%02d', $runyear, $runmonth);

		#request csv report - returns up to 12 months, always starts with january.
		$url = "http://www.stats.oclc.org/cusp/export?expPath=Institution%3A+EBC&group=&networkCode=&stateCode=&countryCode=&report=institutionMonthlyDatabaseUsage&instSymbol=EBC&authorization=&consortiumId=&subgroupId=&libraryType=&tabname=ctr&detail=&lenderInstSymbol=&borrowerInstSymbol=&groupId=&uiType=&commandGroup=&startDate=&exportFormat=csv&numDays=&libraryType=&yyyymm=$yyyymm&numMonths=7&searchInst=EBC&searchAutho=";
		$response = $ua->request(GET $url);
		if (!$response->is_success) {
			die "#error:$0: GET request report $url : " . $response->status_line;
		};

		$content=$response->decoded_content;

		# save contents for possible debugging
		savecontent('FirstSearch', "$collegeid-$runyear", $content);
		
		my @contents = split ("\n", $content);

		my $datasource;

		# grab the dates off of the header lines, first four columns are not dates
		my @periods = ('','','','');	
		my $begperiod = myperiod($begyear, $begmonth);
		my $endperiod = myperiod($endyear, $endmonth);
		my $begperiodndx = 4;
		my $endperiodndx = 4;

		while ($contents[4] =~ /(?<month>\w+)-(?<year>\d{4})/g) {
			my $period = myperiod($+{year},$+{month});
			$begperiodndx++ if ($period lt $begperiod);
			$endperiodndx++ if ($period lt $endperiod);
			push @periods, $period;
		}
		$endperiodndx-- if $endperiodndx == 16;	# prevent multiyear problem

		my @sessions=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
		my @searches=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);

		my $csv = Text::CSV->new({binary => 1});

		# parse each csv line, start with line 5 to 1 before the end
		foreach my $content (@contents[5..$#contents]) {

			if ($csv->parse($content)) {
				my @columns = $csv->fields();
				if ($columns[0] eq '') {
					foreach my $i ($begperiodndx..$endperiodndx) {
						my $period  = $periods[$i];
						my $session = $sessions[$i];
						my $search  = $searches[$i];
						print "$vendorid $collegeid $period $datasource $session $search\n";
						$sthstats->execute($vendorid, $collegeid, $datasource, $period, $session,1)
							or die '#error: estats execute 1 failed';
						$sthstats->execute($vendorid, $collegeid, $datasource, $period, $search, 2)
							or die '#error: estats execute 2 failed';
					};
					@sessions=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
					@searches=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
					next;
				}

				$datasource = $columns[0];
				if ($columns[3] eq 'Sessions') {
					@sessions = @columns;
				}
				else {
					@searches = @columns;
				}
			}
			else {
				my $err = $csv->error_input;
				print "#error:$0: csv parse error : $err\n";
			}
		}

		# advance to the next year. if we hit the end year, set the end month to end year.
		$runyear++;
		$runmonth = $endmonth if ($runyear==$endyear);
	}
}